﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Data;
using MES.DataGateway.DBUtility;
using System.Collections;
using Newtonsoft.Json;

namespace MESWebService
{
    public class QmsToMesBusiness
    {
        /// <summary>
        /// 军检项目推送接口 add by longb 2022-12-27
        /// </summary>
        /// <param name="mesDoc"></param>
        /// <returns></returns>
        public string sendArmyCheckList(XmlNode mesDoc)
        {
            var arrList = new ArrayList();
            var InsertSQL = @"INSERT INTO ArmyCheckDirInfo(ArmyCheckDirInfoID,ArmyYear,productModel,checkCustomer,armyCheckType,branchFactory,partDesc,partName,ProcessNo,specNo,specName,SpecDesc,Notes,isuse,armyCheckListId,armyCheckListSubId,CreateDate)
                                VALUES(lower(sys_guid()),'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}',sysdate)";
            var JsonDic = JsonConvert.DeserializeObject<Dictionary<string, object>>(mesDoc.InnerText);
            var year = JsonDic["year"].ToString();//年度
            var productModel = JsonDic["productModel"].ToString();//产品型号
            var checkCustomer = JsonDic["checkCustomer"].ToString();//验收客户
            var armyCheckType = JsonDic["armyCheckType"].ToString();//军检类型
            var branchFactory = JsonDic["branchFactory"].ToString();//分厂
            var status = JsonDic["status"] == null ? "" : JsonDic["status"].ToString();//状态
            var armyCheckListId = JsonDic["armyCheckListId"];//主表ID
            var armyCheckListSubList = JsonConvert.DeserializeObject<DataTable>(JsonDic["armyCheckListSubList"].ToString());//军检零组件详情 
            foreach (DataRow row in armyCheckListSubList.Rows)
            {
                var partName = row["partName"].ToString();//零组件名称
                var partCode = row["partCode"].ToString();//零组件号
                var processes = row["processes"].ToString();//工序号
                var armyCheckContent = row["armyCheckContent"].ToString();//军检内容
                var craftRulesNo = row["craftRulesNo"].ToString();//工艺规程号
                var remark = row["remark"].ToString();//备注
                status = status.Equals("1") ? "1" : row["status"].ToString();//状态(主表若删除，则细表默认删除) 0为有效、1为无效
                var armyCheckListSubId = row["armyCheckListSubId"];//细表ID
                //var selectSQL = @"SELECT ArmyCheckDirInfoID FROM  ArmyCheckDirInfo WHERE  ARMYCHECKTYPE='{0}' AND ARMYYEAR='{1}' AND BRANCHFACTORY='{2}' AND PARTNAME='{3}' AND PROCESSNO='{4}'AND SPECNO='{5}' ";
                var selectSQL = @"SELECT ArmyCheckDirInfoID FROM  ArmyCheckDirInfo WHERE ARMYCHECKLISTSUBID='{0}' and ARMYCHECKLISTID='{1}'";
                DataTable dt = OracleHelper.Query(string.Format(selectSQL, armyCheckListSubId, armyCheckListId)).Tables[0];//armyCheckType, year, branchFactory, partCode, craftRulesNo, processes)).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    var updateSQL = @"UPDATE ArmyCheckDirInfo SET NOTES='{0}',SPECDESC='{1}',ISUSE='{2}' WHERE ArmyCheckDirInfoID='{3}'";
                    arrList.Add(string.Format(updateSQL, remark, armyCheckContent, status, dt.Rows[0]["ArmyCheckDirInfoID"].ToString()));
                }
                else
                {
                    arrList.Add(string.Format(InsertSQL, year, productModel, checkCustomer, armyCheckType, branchFactory, partName, partCode, craftRulesNo, processes, "", armyCheckContent, remark, status, armyCheckListId, armyCheckListSubId));
                }
            }
            var msg = string.Empty;
            var result = OracleHelper.ExecuteSqlTran(arrList, ref msg);
            var resultDic = string.Empty;
            if (result)
            {
                resultDic = "<TETTYP><RTYPE>S</RTYPE><RTMSG>军检目录信息接收成功</RTMSG></TETTYP>";
            }
            else
            {
                resultDic = "<TETTYP><RTYPE>E</RTYPE><RTMSG>军检目录信息接收失败：" + msg + "</RTMSG></TETTYP>";
            }
            return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess><message>true</message></header><document><![CDATA[" + resultDic + "]]></document></ReqMsg>";
        }

        /// <summary>
        /// 理化试验结果集成接口(返回) add by longb 2023-03-06
        /// </summary>
        /// <param name="mesDoc"></param>
        /// <returns></returns>
        public string receiveIqsResult(XmlNode mesDoc,string strXML)
        {
            var arrList = new ArrayList();
            var updateSQL = @"update {10} set Status='{0}',IqsOrderQMSNoLH='{1}', FinishReportTime=to_date('{2}','yyyy-MM-dd hh24:mi:ss'),
                              TestResult='{3}',SendEmployeeName='{4}',SendDate=to_date('{5}','yyyy-MM-dd hh24:mi:ss'),RecvEmployeeName='{6}',
                              RecvDate=to_date('{7}','yyyy-MM-dd hh24:mi:ss'),TreatNote='{8}',reportUrl='{9}' {11} where QMSENTRUSTNAME='{12}'";
            var EntrustName = mesDoc.SelectSingleNode("entrustName").InnerText;//请托单号
            var Status = mesDoc.SelectSingleNode("status").InnerText;//状态
            var IqsOrderQMSNoLH = mesDoc.SelectSingleNode("iqsOrderQMSNoLH").InnerText;//试验报告单号
            var FinishReportTime = mesDoc.SelectSingleNode("finishReportTime").InnerText;//报告完成日期
            var TestResult = mesDoc.SelectSingleNode("testResult").InnerText;//试验结果
            var SendEmployeeName = mesDoc.SelectSingleNode("sendEmployeeName").InnerText;//送料人
            var SendDate = mesDoc.SelectSingleNode("sendDate").InnerText;//送样时间
            var RecvEmployeeName = mesDoc.SelectSingleNode("recvEmployeeName").InnerText;//取样人
            var RecvDate = mesDoc.SelectSingleNode("recvDate").InnerText;//取样时间
            var Note = mesDoc.SelectSingleNode("note").InnerText;//备注
            var reportUrl = mesDoc.SelectSingleNode("reportUrl").InnerText;//理化报告链接地址
            var exist = OracleHelper.GetSingle(string.Format(@"select QMSENTRUSTNAME from EntrustMeasurement where QMSENTRUSTNAME='{0}'", EntrustName));
            if (exist!=null)
            {
                arrList.Add(string.Format(updateSQL, Status, IqsOrderQMSNoLH, FinishReportTime, TestResult, SendEmployeeName, SendDate, RecvEmployeeName, RecvDate, Note, reportUrl, "EntrustMeasurement", "", EntrustName));
            }
            exist = OracleHelper.GetSingle(string.Format(@"select QMSENTRUSTNAME from EntrustMeasurement2 where QMSENTRUSTNAME='{0}'", EntrustName));
            if (exist != null)
            {
                arrList.Add(string.Format(updateSQL, Status, IqsOrderQMSNoLH, FinishReportTime, TestResult, SendEmployeeName, SendDate, RecvEmployeeName, RecvDate, Note, reportUrl, "EntrustMeasurement2", ",resultXml='" + strXML + "'", EntrustName));
            }
            var msg = string.Empty;
            var result = OracleHelper.ExecuteSqlTran(arrList, ref msg);
            var resultDic = string.Empty;
            if (result)
            {
                return RespMsg("true", "接收数据成功", "S", "理化试验结果接收成功");
            }
            else
            {
                return RespMsg("true", "接收数据成功", "E", "理化试验结果接收失败：" + msg);
            }
        }

        /// <summary>
        /// QMS工序军检返回接口 add by zhangrj 2022-12-26
        /// </summary>
        /// <param name="mesDoc"></param>
        /// <returns></returns>
        public string QMS_Send_SpecMilitaryCheckInfoResult_Service(XmlNode mesDoc)
        {
            string mfgOrderName = mesDoc.SelectSingleNode("mfgOrderName").InnerText;//订单号
            string containerName = mesDoc.SelectSingleNode("containerName").InnerText;//批次号
            string productName = mesDoc.SelectSingleNode("productName").InnerText;//件号
            string specNo = mesDoc.SelectSingleNode("specNo").InnerText;//工序号
            //查询mes是否有军检提交,未反馈的数据
            string strSql = "select * from ArmyCheckSendToQMS ac WHERE ac.containername = '{0}' AND ac.mfgordername = '{1}' AND ac.specno = '{2}'";
            DataTable dt = OracleHelper.Query(string.Format(strSql, containerName, mfgOrderName, specNo)).Tables[0];
            if (dt.Rows.Count == 0)
            {
                return RespMsg("true", "接收数据成功", "E", "未找到工序军检提交记录");
                //return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + "未找到工序军检提交记录" + "</document></ReqMsg>";
            }
            string acceptanceQty = mesDoc.SelectSingleNode("acceptanceQty").InnerText;//确认合格数
            string reworkQty = mesDoc.SelectSingleNode("reworkQty").InnerText;//返修数
            string lossQty = mesDoc.SelectSingleNode("lossQty").InnerText;//报废数
            string customerName = mesDoc.SelectSingleNode("customerName").InnerText;//顾客代表
            string customerDealDate = mesDoc.SelectSingleNode("customerDealDate").InnerText;//顾客代表审核时间

            //更新数据
            int i = OracleHelper.ExecuteSql(string.Format(@"UPDATE ArmyCheckSendToQMS ac SET ac.qms_customername = '{0}',ac.qms_dealdate = to_date('{1}','yyyy-MM-dd HH24:mi:ss')
,ac.qms_lossqty = '{2}',ac.qms_pssqty = '{3}',ac.qms_reworkqty = '{4}' WHERE ac.armychecksendtoqmsid = '{5}'",
customerName, customerDealDate, lossQty, acceptanceQty, reworkQty, dt.Rows[0]["Armychecksendtoqmsid"].ToString()));
            if (i > 0)
            {
                return RespMsg("true", "接收数据成功", "S", "处理成功");
                //return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + "处理成功" + "</document></ReqMsg>";
            }
            else
            {
                return RespMsg("false", "接收数据成功", "E", "数据库处理失败");
                //return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + "数据库处理失败" + "</document></ReqMsg>";
            }
        }

        /// <summary>
        /// QMS产品军检结果接口
        /// add:Wangjh 20221221
        /// </summary>
        /// <param name="mesDoc"></param>
        /// <returns></returns>
        public string QMSArmyInstoreResult(XmlNode mesDoc)
        {
            string productName = mesDoc.SelectSingleNode("productName").InnerText;
            string realContainerNo = mesDoc.SelectSingleNode("productBatchNo").InnerText;
            //查询mes是否有军检提交,未反馈的数据
            string strSql = "select * from containerinstore ci where ci.charg='{0}' and ci.isuse=0 and ci.QMS_CusAuditDate is null";
            DataTable dt = OracleHelper.Query(string.Format(strSql, productName + "/" + realContainerNo)).Tables[0];
            if (dt.Rows.Count == 0)
            {
                return RespMsg("true", "接收数据成功", "E", "未找到产品军检入库记录");
                //return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + "未找到产品军检入库记录" + "</document></ReqMsg>";
            }

            Dictionary<string, string> para = new Dictionary<string, string>();
            //取值
            para.Add("QMS_Passqty", mesDoc.SelectSingleNode("acceptanceQty").InnerText);
            para.Add("QMS_RepairQty", mesDoc.SelectSingleNode("reworkQty").InnerText);
            para.Add("QMS_LossQty", mesDoc.SelectSingleNode("lossQty").InnerText);
            para.Add("QMS_Customer", mesDoc.SelectSingleNode("customerName").InnerText);
            para.Add("QMS_CusAuditDate", mesDoc.SelectSingleNode("customerDealDate").InnerText);

            //更新数据
            var i = OracleHelper.ExecuteSql(string.Format(@"update containerinstore ci set ci.qms_passqty={0},ci.qms_repairqty='{1}',ci.qms_lossqty='{2}',ci.qms_customer='{3}',
ci.qms_cusauditdate=to_date('{4}','yyyy/mm/dd hh24:mi:ss') where ci.containerinstoreid='{5}' ", para["QMS_Passqty"], para["QMS_RepairQty"], para["QMS_LossQty"],
                                                                                                 para["QMS_Customer"], para["QMS_CusAuditDate"], dt.Rows[0]["containerinstoreid"].ToString()));
            if (i > 0)
            {
                return RespMsg("true", "接收数据成功", "S", "处理成功");
                //return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + "处理成功" + "</document></ReqMsg>";
            }
            else
            {
                return RespMsg("true", "接收数据成功", "E", "数据库处理失败");
                //return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + "数据库处理失败" + "</document></ReqMsg>";
            }
        }

        /// <summary>
        /// 排故单审理结果接口 
        /// add by longb 2023-04-13
        /// </summary>
        /// <param name="mesDoc"></param>
        /// <returns></returns>
        public string DealFaultBillResult(XmlNode mesDoc)
        {
            string MfgOrderName = mesDoc.SelectSingleNode("mfgOrderName").InnerText;//订单号
            string EngineNO = mesDoc.SelectSingleNode("engineNo").InnerText;//发动机号
            string DealFaultBillName = mesDoc.SelectSingleNode("dealFaultBillName").InnerText;//排故单号
            string CustomerName = mesDoc.SelectSingleNode("customerName").InnerText;//客户名称
            string CustomerDealDate = mesDoc.SelectSingleNode("customerDealDate").InnerText;//客户确认时间

            var updateSQL = @"update DealFaultBill set AuditDate=to_date('{0}','yyyy-MM-dd hh24:mi:ss'),
                                AuditEmployeeName='{1}',TRANSFERSTATUS='2' --(select EmployeeID from Employee where FullName='{1}') 
                                where DealFaultBillName='{2}'";
            updateSQL = string.Format(updateSQL, CustomerDealDate, CustomerName, DealFaultBillName);
            if (OracleHelper.ExecuteSql(updateSQL) > 0)
            {
                return RespMsg("true", "接收数据成功", "S", "排故单审理结果接收成功");
            }
            else
            {
                return RespMsg("true", "接收数据成功", "E", "排故单审理结果接收失败");
            }
        }

        /// <summary>
        /// 排故单处理结果审理接口 
        /// add by longb 2023-04-13
        /// </summary>
        /// <param name="mesDoc"></param>
        /// <returns></returns>
        public string DealFaultBillResolveResult(XmlNode mesDoc)
        {
            string MfgOrderName = mesDoc.SelectSingleNode("mfgOrderName").InnerText;//订单号
            string EngineNO = mesDoc.SelectSingleNode("engineNo").InnerText;//发动机号
            string DealFaultBillName = mesDoc.SelectSingleNode("dealFaultBillName").InnerText;//排故单号
            string CustomerName = mesDoc.SelectSingleNode("customerName").InnerText;//客户名称
            string CustomerDealDate = mesDoc.SelectSingleNode("customerDealDate").InnerText;//客户确认时间
            string FaultBillContainerName = mesDoc.SelectSingleNode("faultBillContainerName").InnerText;//排故任务流卡

            var updateSQL = @"update DealFaultBill set FaultBillContainerName='{0}',ResultAuditDate=to_date('{1}','yyyy-MM-dd hh24:mi:ss'),
                                ResultAuditEmployeeName='{2}'--(select EmployeeID from Employee where FullName='{2}') 
                                where DealFaultBillName='{3}'";
            updateSQL = string.Format(updateSQL, FaultBillContainerName, CustomerDealDate, CustomerName, DealFaultBillName);
            if (OracleHelper.ExecuteSql(updateSQL) > 0)
            {
                return RespMsg("true", "接收数据成功", "S", "排故单处理结果审理接收成功");
            }
            else
            {
                return RespMsg("true", "接收数据成功", "E", "排故单处理结果审理接收失败");
            }
        }

        /// <summary>
        /// 故检提交单审理结果接口
        /// add by longb 2023-04-13 
        /// </summary>
        /// <param name="mesDoc"></param>
        /// <returns></returns>
        public string ZSGJCheckSubmitBillResult(XmlNode mesDoc)
        {
            string ZSGJCheckSubmitBillNo = mesDoc.SelectSingleNode("zsgjcheckSubmitBillNo").InnerText;//故检提交单号
            string AuditEmployeeFullName = mesDoc.SelectSingleNode("auditEmployeeFullName").InnerText;//审核人
            string AuditDate = mesDoc.SelectSingleNode("auditDate").InnerText;//审核时间
            string Conclusion = mesDoc.SelectSingleNode("conclusion").InnerText;//顾客代表结论
            var updateSQL = @"update ZSGJCheckSubmitBill set Conclusion='{0}',AuditDate=to_date('{1}','yyyy-MM-dd hh24:mi:ss'),
                                AuditEmployeeID=(select EmployeeID from Employee where FullName='{2}') where ZSGJCheckSubmitBillNo='{3}'";
            updateSQL = string.Format(updateSQL, Conclusion, AuditDate, AuditEmployeeFullName, ZSGJCheckSubmitBillNo);
            if (OracleHelper.ExecuteSql(updateSQL) > 0)
            {
                return RespMsg("true", "接收数据成功", "S", "故检提交单审理结果接收成功");
            }
            else
            {
                return RespMsg("true", "接收数据成功", "E", "故检提交单审理结果接收失败");
            }
        }
        /// <summary>
        /// 周转/串件审理结果接口
        /// add by longb 2023-04-13 
        /// </summary>
        /// <param name="mesDoc"></param>
        /// <returns></returns>
        public string ExchangeBillResult(XmlNode mesDoc)
        {
            string ExchangeName = mesDoc.SelectSingleNode("exchangeName").InnerText;//周转/串件单号
            string GCJSB_EmployeeName = mesDoc.SelectSingleNode("gcjsbEmployeeName").InnerText;//工程技术部人员
            string GCJSB_AuditDate = mesDoc.SelectSingleNode("gcjsbAuditDate").InnerText;//工程技术部审批时间
            string JYJCSYB_EmployeeName = mesDoc.SelectSingleNode("jyjcsybEmployeeName").InnerText;//检验检测事业部人员
            string JYJCSYB_AuditDate = mesDoc.SelectSingleNode("jyjcsybAuditDate").InnerText;//检验检测事业部审批时间
            string SCZHB_EmployeeName = mesDoc.SelectSingleNode("sczhbEmployeeName").InnerText;//生产指挥部人员
            string SCZHB_AuditDate = mesDoc.SelectSingleNode("sczhbAuditDate").InnerText;//生产指挥部审批时间
            string CustomerName = mesDoc.SelectSingleNode("customerName").InnerText;//顾客代表
            string CustomerDealDate = mesDoc.SelectSingleNode("customerDealDate").InnerText;//顾客代表审核时间

            var updateSQL = @"update ExchangeBill set 
                                GCJSB_EmployeeID=(select EmployeeID from Employee where FullName='{0}'),GCJSB_AuditDate=to_date('{1}','yyyy-MM-dd hh24:mi:ss'),
                                JYJCSYB_EmployeeID=(select EmployeeID from Employee where FullName='{2}'),JYJCSYB_AuditDate=to_date('{3}','yyyy-MM-dd hh24:mi:ss'),
                                SCZHB_EmployeeID=(select EmployeeID from Employee where FullName='{4}'),SCZHB_AuditDate=to_date('{5}','yyyy-MM-dd hh24:mi:ss'),
                                CustomerName='{6}',CustomerDealDate=to_date('{7}','yyyy-MM-dd hh24:mi:ss') where ExchangeName='{8}'";
            updateSQL = string.Format(updateSQL, GCJSB_EmployeeName, GCJSB_AuditDate, JYJCSYB_EmployeeName, JYJCSYB_AuditDate, SCZHB_EmployeeName, SCZHB_AuditDate, CustomerName, CustomerDealDate, ExchangeName);
            if (OracleHelper.ExecuteSql(updateSQL) > 0)
            {
                return RespMsg("true", "接收数据成功", "S", "周转/串件审理结果接收成功");
            }
            else
            {
                return RespMsg("true", "接收数据成功", "E", "周转/串件审理结果接收失败");
            }
        }

        #region longbin 质量接口
        #region 系统质量问题审理结果接口--
        //[WebMethod]
        public string qaProblemHearResultNotify(XmlNode mesDoc)
        {
            string dealName = mesDoc.SelectSingleNode("dealName").InnerText;//质量问题单号
            string orderNo = mesDoc.SelectSingleNode("orderNo").InnerText;//订单号
            string hearResult = mesDoc.SelectSingleNode("hearResult").InnerText;//审理结果
            string remark = mesDoc.SelectSingleNode("remark").InnerText;//审理备注
            //string remark = mesDoc.SelectSingleNode("remark").InnerText;//最终处理意见
            var para = new Dictionary<string, string>();
            para.Add("dealName", dealName);
            para.Add("orderNo", orderNo);
            para.Add("hearResult", hearResult);
            para.Add("remark", remark);
            if (updateQualityHistoryRecord(para))
            {
                return RespMsg("true", "接收数据成功", "S", "系统质量问题审理结果接收成功");
            }
            else
            {
                return RespMsg("true", "接收数据成功", "E", "系统质量问题审理结果接收失败");
            }
        }
        #endregion

        #region 首件鉴定目录接口--
        //[WebMethod]
        public string firstThingAuth(XmlNode mesDoc)
        {
            string firstThingAuthDirId = mesDoc.SelectSingleNode("firstThingAuthDirId").InnerText;//首件鉴定目录ID
            string componentsImgNo = mesDoc.SelectSingleNode("componentsImgNo").InnerText;//零组件图号
            string componentsName = mesDoc.SelectSingleNode("componentsName").InnerText;//零组件名称
            string keyImptFileLogo = mesDoc.SelectSingleNode("keyImptFileLogo").InnerText;//关重件标识
            string craftVersionNo = mesDoc.SelectSingleNode("craftVersionNo").InnerText;//工艺版本号
            string crdLevel = mesDoc.SelectSingleNode("crdLevel").InnerText;//级别
            string mainBuildUnit = mesDoc.SelectSingleNode("mainBuildUnit").InnerText;//主制单位
            string remark = mesDoc.SelectSingleNode("remark").InnerText;//备注
            var para = new Dictionary<string, string>();
            if (string.IsNullOrWhiteSpace(firstThingAuthDirId)) { return RespMsg("false", "接收数据失败", "2", "首件鉴定目录字段【firstThingAuthDirId】不能为空"); }
            if (string.IsNullOrWhiteSpace(componentsImgNo)) { return RespMsg("false", "接收数据失败", "2", "零组件图号字段【componentsImgNo】不能为空"); }
            if (string.IsNullOrWhiteSpace(componentsName)) { return RespMsg("false", "接收数据失败", "2", "零组件名称字段【componentsName】不能为空"); }
            if (string.IsNullOrWhiteSpace(keyImptFileLogo)) { return RespMsg("false", "接收数据失败", "2", "关重件标识字段【keyImptFileLogo】不能为空"); }
            if (string.IsNullOrWhiteSpace(craftVersionNo)) { return RespMsg("false", "接收数据失败", "2", "工艺版本号字段【craftVersionNo】不能为空"); }
            if (string.IsNullOrWhiteSpace(crdLevel)) { return RespMsg("false", "接收数据失败", "2", "级别字段【crdLevel】不能为空"); }
            if (string.IsNullOrWhiteSpace(mainBuildUnit)) { return RespMsg("false", "接收数据失败", "2", "主制单位字段【mainBuildUnit】不能为空"); }
            para.Add("firstThingAuthDirId", firstThingAuthDirId);
            para.Add("componentsNo", componentsImgNo);
            para.Add("componentsName", componentsName);
            para.Add("keyImptFileLogo", keyImptFileLogo);
            para.Add("VersionNo", craftVersionNo);
            para.Add("Level", crdLevel);
            para.Add("BuildUnit", mainBuildUnit);
            para.Add("remark", remark);
            para.Add("IdentifyType", "1");
            if (InsertFirstIdentifyProduct(para))
            {
                return RespMsg("true", "接收数据成功", "S", "首件鉴定目录接收成功");
            }
            else
            {
                return RespMsg("true", "接收数据成功", "E", "首件鉴定目录接收失败");
            }
        }
        #endregion

        #region 首件鉴定控制点解除接口
        //[WebMethod]
        public string firstThingAuthDirControlPointRelease(XmlNode mesDoc)
        {
            string firstThingAuthDirId = mesDoc.SelectSingleNode("firstThingAuthDirId").InnerText;//首件鉴定目录ID
            string componentsImgNo = mesDoc.SelectSingleNode("componentsImgNo").InnerText;//零组件图号
            string componentsName = mesDoc.SelectSingleNode("componentsName").InnerText;//零组件名称
            string craftVersionNo = mesDoc.SelectSingleNode("craftVersionNo").InnerText;//工艺版本号
            string authCompleteDate = mesDoc.SelectSingleNode("authCompleteDate").InnerText;//鉴定完成日期
            string remark = mesDoc.SelectSingleNode("remark").InnerText;//备注
            var para = new Dictionary<string, string>();
            if (string.IsNullOrWhiteSpace(firstThingAuthDirId)) { return RespMsg("false", "接收数据失败", "2", "首件鉴定目录字段【firstThingAuthDirId】不能为空"); }
            para.Add("FirstIdentifyProductID", firstThingAuthDirId);
            para.Add("IdentifyType", "1");
            if (UpdateFirstIdentifyProduct(para))
            {
                return RespMsg("true", "接收数据成功", "S", "首件鉴定控制点解除成功");
            }
            else
            {
                return RespMsg("true", "接收数据成功", "E", "首件鉴定控制点解除失败");
            }

        }
        #endregion

        #region 质量评审目录接口--
        //[WebMethod]
        public string pushQaProductReviewDir(XmlNode mesDoc)
        {
            string qaProductReviewDirId = mesDoc.SelectSingleNode("qaProductReviewDirId").InnerText;//产品质量评审目录ID
            string componentsNo = mesDoc.SelectSingleNode("componentsNo").InnerText;//零(组)件号
            string componentsName = mesDoc.SelectSingleNode("componentsName").InnerText;//零(组)件名称
            string qprdLevel = mesDoc.SelectSingleNode("qprdLevel").InnerText;//级别
            string constructUnit = mesDoc.SelectSingleNode("constructUnit").InnerText;//主制单位
            string remark = mesDoc.SelectSingleNode("remark").InnerText;//备注
            if (string.IsNullOrWhiteSpace(qaProductReviewDirId)) { return RespMsg("false", "接收数据失败", "2", "产品质量评审目录字段【qaProductReviewDirId】不能为空"); }
            if (string.IsNullOrWhiteSpace(componentsNo)) { return RespMsg("false", "接收数据失败", "2", "零(组)件号字段【componentsNo】不能为空"); }
            if (string.IsNullOrWhiteSpace(componentsName)) { return RespMsg("false", "接收数据失败", "2", "零(组)件名称字段【componentsName】不能为空"); }
            if (string.IsNullOrWhiteSpace(qprdLevel)) { return RespMsg("false", "接收数据失败", "2", "级别字段【qprdLevel】不能为空"); }
            if (string.IsNullOrWhiteSpace(constructUnit)) { return RespMsg("false", "接收数据失败", "2", "主制单位字段【constructUnit】不能为空"); }
            var para = new Dictionary<string, string>();
            para.Add("firstThingAuthDirId", qaProductReviewDirId);
            para.Add("componentsNo", componentsNo);
            para.Add("componentsName", componentsName);
            para.Add("keyImptFileLogo", "");
            para.Add("VersionNo", "");
            para.Add("Level", qprdLevel);
            para.Add("BuildUnit", constructUnit);
            para.Add("remark", remark);
            para.Add("IdentifyType", "2");
            if (InsertFirstIdentifyProduct(para))
            {
                return RespMsg("true", "接收数据成功", "S", "质量评审目录接收成功");
            }
            else
            {
                return RespMsg("true", "接收数据成功", "E", "质量评审目录接收失败");
            }
        }
        #endregion

        #region 产品质量评审控制点解除接口
        //[WebMethod]
        public string qaProductReviewDirControlPointRelease(XmlNode mesDoc)
        {
            string qaProductReviewDirId = mesDoc.SelectSingleNode("qaProductReviewDirId").InnerText;//产品质量评审目录ID
            string componentsNo = mesDoc.SelectSingleNode("componentsNo").InnerText;//零(组)件号
            string componentsName = mesDoc.SelectSingleNode("componentsName").InnerText;//零(组)件名称
            string reviewCompleteDate = mesDoc.SelectSingleNode("reviewCompleteDate").InnerText;//评审完成日期
            if (string.IsNullOrWhiteSpace(qaProductReviewDirId)) { return RespMsg("false", "接收数据失败", "2", "产品质量评审目录字段【qaProductReviewDirId】不能为空"); }
            var para = new Dictionary<string, string>();
            para.Add("FirstIdentifyProductID", qaProductReviewDirId);
            para.Add("IdentifyType", "2");
            if (UpdateFirstIdentifyProduct(para))
            {
                return RespMsg("true", "接收数据成功", "S", "产品质量评审控制点解除成功");
            }
            else
            {
                return RespMsg("true", "接收数据成功", "E", "产品质量评审控制点解除失败");
            }
        }
        #endregion

        #region 工艺评审控制点接口
        //[WebMethod]
        public string pushCraftReviewDir(XmlNode mesDoc)
        {
            string craftReviewDirId = mesDoc.SelectSingleNode("craftReviewDirId").InnerText;//工艺评审目录ID ---开卡使用
            string reviewFileNo = mesDoc.SelectSingleNode("reviewFileNo").InnerText;//评审文件号(零件号)
            string fileName = mesDoc.SelectSingleNode("fileName").InnerText;//文件名称(零件名称)
            string keyImptFileLogo = mesDoc.SelectSingleNode("keyImptFileLogo").InnerText;//关重件标识
            string crdLevel = mesDoc.SelectSingleNode("crdLevel").InnerText;//级别
            string constructUnit = mesDoc.SelectSingleNode("constructUnit").InnerText;//主制单位
            string remark = mesDoc.SelectSingleNode("remark").InnerText;//备注
            if (string.IsNullOrWhiteSpace(craftReviewDirId)) { return RespMsg("false", "接收数据失败", "2", "工艺评审目录字段【craftReviewDirId】不能为空"); }
            if (string.IsNullOrWhiteSpace(reviewFileNo)) { return RespMsg("false", "接收数据失败", "2", "评审文件号(零件号)字段【reviewFileNo】不能为空"); }
            if (string.IsNullOrWhiteSpace(fileName)) { return RespMsg("false", "接收数据失败", "2", "文件名称(零件名称)字段【fileName】不能为空"); }
            if (string.IsNullOrWhiteSpace(keyImptFileLogo)) { return RespMsg("false", "接收数据失败", "2", "关重件标识字段【keyImptFileLogo】不能为空"); }
            if (string.IsNullOrWhiteSpace(crdLevel)) { return RespMsg("false", "接收数据失败", "2", "级别字段【crdLevel】不能为空"); }
            if (string.IsNullOrWhiteSpace(constructUnit)) { return RespMsg("false", "接收数据失败", "2", "主制单位字段【constructUnit】不能为空"); }

            var para = new Dictionary<string, string>();
            para.Add("firstThingAuthDirId", craftReviewDirId);
            para.Add("componentsNo", reviewFileNo);
            para.Add("componentsName", fileName);
            para.Add("keyImptFileLogo", keyImptFileLogo);
            para.Add("VersionNo", "");
            para.Add("Level", crdLevel);
            para.Add("BuildUnit", constructUnit);
            para.Add("remark", remark);
            para.Add("IdentifyType", "3");
            if (InsertFirstIdentifyProduct(para))
            {
                return RespMsg("true", "接收数据成功", "S", "工艺评审控制点接收成功");
            }
            else
            {
                return RespMsg("true", "接收数据成功", "E", "工艺评审控制点接收失败");
            }
        }
        #endregion

        #region 工艺评审控制点解除接口
        //[WebMethod]
        public string craftReviewDirControlPointRelease(XmlNode mesDoc)
        {
            string craftReviewDirId = mesDoc.SelectSingleNode("craftReviewDirId").InnerText;//工艺评审目录ID
            string reviewFileNo = mesDoc.SelectSingleNode("reviewFileNo").InnerText;//零(组)件号
            string fileName = mesDoc.SelectSingleNode("fileName").InnerText;//零(组)件名称
            string reviewCompleteDate = mesDoc.SelectSingleNode("reviewCompleteDate").InnerText;//评审完成日期
            if (string.IsNullOrWhiteSpace(craftReviewDirId)) { return RespMsg("false", "接收数据失败", "2", "工艺评审目录字段【constructUnit】不能为空"); }
            var para = new Dictionary<string, string>();
            para.Add("FirstIdentifyProductID", craftReviewDirId);
            para.Add("IdentifyType", "3");
            if (UpdateFirstIdentifyProduct(para))
            {
                return RespMsg("true", "接收数据成功", "1", "工艺评审控制点解除成功");
            }
            else
            {
                return RespMsg("true", "接收数据成功", "2", "工艺评审控制点解除失败");
            }
        }
        #endregion

        public string RespMsg(string isSuccess, string message, string success, string dmessage)
        {
            return string.Format("<?xml version=\"1.0\" encoding=\"UTF-8\"?><RespMsg><header><sysName>APP_MES</sysName><isSuccess>{0}</isSuccess><message>{1}</message></header><document><![CDATA[<TETTYP><RTYPE>{2}</RTYPE><RTMSG>{3}</RTMSG></TETTYP>]]></document></RespMsg>", isSuccess, message, success, dmessage);
        }
        public string RespMsg(string isSuccess, string message)
        {
            return string.Format("<?xml version=\"1.0\" encoding=\"UTF-8\"?><RespMsg><header><sysName>APP_MES</sysName><isSuccess>{0}</isSuccess><message>{1}</message></header><document></document></RespMsg>", isSuccess, message);
        }
        #endregion

        #region 业务方法
        #region 系统质量问题审理结果--更新
        /// <summary>
        /// 系统质量问题审理结果--更新
        /// </summary>
        /// <returns></returns>
        public Boolean updateQualityHistoryRecord(Dictionary<string, string> para)
        {
            Boolean result = false;
            try
            {
                string strSql = "UPDATE QualityHistoryRecord SET QMSRESULT='{0}',QMSRESULTNOTES='{1}' WHERE DEALNAME='{2}' AND MFGORDERNAME='{3}'";
                string ExcSql = string.Format(strSql, para["hearResult"], para["remark"], para["dealName"], para["orderNo"]);
                int count = OracleHelper.ExecuteSql(ExcSql);
                if (count > 0)
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }
        #endregion

        #region 首件鉴定目录，质量评审目录--插入
        public Boolean InsertFirstIdentifyProduct(Dictionary<string, string> para)
        {
            Boolean result = false;
            try
            {
                string selectSQL = @"select * from FirstIdentifyProduct where IDENTIFYTYPE='{0}' and FIRSTIDENTIFYPRODUCTID='{1}'";
                DataTable dt = OracleHelper.Query(string.Format(selectSQL, para["IdentifyType"], para["firstThingAuthDirId"])).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    var updateDQL = @"update FirstIdentifyProduct set PRODUCTNAME='{0}',KEYIMPTFILELOGO='{1}',VERSIONNO='{2}',qprdLevel='{3}',BUILDUNIT='{4}',REMARK='{5}',DRAWINGNO='{6}' where  IDENTIFYTYPE='{7}' and FIRSTIDENTIFYPRODUCTID='{8}'";
                    var ExcSql = string.Format(updateDQL, para["componentsName"], para["keyImptFileLogo"], para["VersionNo"], para["Level"], para["BuildUnit"], para["remark"], para["componentsNo"], para["IdentifyType"], para["firstThingAuthDirId"]);
                    if (OracleHelper.ExecuteSql(ExcSql) > 0) { result = true; }
                }
                else
                {
                    string strSql = @"INSERT INTO FirstIdentifyProduct(FIRSTIDENTIFYPRODUCTID, IDENTIFYTYPE, PRODUCTNAME, STATUS, KEYIMPTFILELOGO, VERSIONNO,qprdLevel, BUILDUNIT, REMARK, DRAWINGNO)
                                VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}')";
                    string ExcSql = string.Format(strSql, para["firstThingAuthDirId"], para["IdentifyType"], para["componentsName"], "0", para["keyImptFileLogo"], para["VersionNo"], para["Level"], para["BuildUnit"], para["remark"], para["componentsNo"]);
                    int count = OracleHelper.ExecuteSql(ExcSql);
                    if (count > 0)
                    {
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }

        #endregion

        #region 首件鉴定,质量评审控制点解除--更新
        public Boolean UpdateFirstIdentifyProduct(Dictionary<string, string> para)
        {
            Boolean result = false;
            try
            {
                string strSql = "UPDATE FirstIdentifyProduct SET STATUS='1' WHERE FIRSTIDENTIFYPRODUCTID='{0}' AND IDENTIFYTYPE='{1}'";
                string ExcSql = string.Format(strSql, para["FirstIdentifyProductID"], para["IdentifyType"]);
                int count = OracleHelper.ExecuteSql(ExcSql);
                if (count > 0)
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }

        #endregion

        #endregion

        /// <summary>
        /// 1.1检验信息接口
        /// </summary>
        /// <param name="mesDoc"></param>
        /// <returns></returns>
        public string qmsSendCheckInfo(XmlNode mesDoc)
        {
            string containerId = mesDoc.SelectSingleNode("containerID").InnerText;//批次ID
            string workflowstepID = mesDoc.SelectSingleNode("workflowstepID").InnerText;//工序ID
            string containerStepWorkReportID = mesDoc.SelectSingleNode("containerStepWorkReportID").InnerText;//报工ID
            string checker = mesDoc.SelectSingleNode("checker").InnerText;//检验员工号
            string acceptanceQty = mesDoc.SelectSingleNode("acceptanceQty").InnerText;//合格数
            string lossQty = mesDoc.SelectSingleNode("lossQty").InnerText;//报废数
            string createDate = mesDoc.SelectSingleNode("createDate").InnerText;//检验时间
            string checkNote = mesDoc.SelectSingleNode("checkNote").InnerText;//检验备注
            string finishCheck = mesDoc.SelectSingleNode("finishCheck").InnerText;//是否是成品检验（0:否1:是）
            string checkState = mesDoc.SelectSingleNode("checkState").InnerText;//检验状态
            string scrap = mesDoc.SelectSingleNode("scrap").InnerText;//报废单号
            string lossContainerName = mesDoc.SelectSingleNode("lossContainerName").InnerText;//报废子序号
            string acceptanceContainerName = mesDoc.SelectSingleNode("acceptanceContainerName").InnerText;//合格子序号
            //检验员
            var chekEmployeeid = OracleHelper.GetSingle(string.Format("select e.employeeid from employee e where e.employeename ='{0}'", checker));
            if (chekEmployeeid == null)
            {
                return RespMsg("false", "检验信息接收失败，检验员工号【" + checker + "】在MES系统中不存在");
            }
            #region "工序/成品检验"
            var arrList = new ArrayList();
            var uuid = Guid.NewGuid().ToString();
            if (finishCheck.Equals("0"))//是否是成品检验（0:否1:是）
            {
                var insertSQL = @"INSERT INTO CONTAINERCHECKINFO(containercheckinfoid,containerid,workflowstepid,containerstepworkreportid,checkerid,acceptanceqty,acceptanceqty2,lossqty,createdate,checknote,isuse)
                              values('{0}','{1}','{2}','{3}','{4}','{5}','{5}','{6}',to_date('{7}','yyyy-MM-dd hh24:mi:ss'),'{8}','0')";
                var updateSQL = @"UPDATE CONTAINERCHECKINFO SET checkerid='{0}',acceptanceqty='{1}',lossqty='{2}',checknote='{3}'
                            WHERE containercheckinfoid='{4}'";
                var containercheckinfoid = OracleHelper.GetSingle(string.Format("select containercheckinfoid from CONTAINERCHECKINFO e where e.isuse=0 and e.containerid ='{0}' and workflowstepid='{1}' and containerstepworkreportid='{2}'", containerId, workflowstepID, containerStepWorkReportID));
                if (containercheckinfoid == null)
                {
                    arrList.Add(string.Format(insertSQL, uuid, containerId, workflowstepID, containerStepWorkReportID, chekEmployeeid, acceptanceQty, lossQty, createDate, checkNote));
                }
                else
                {
                    arrList.Add(string.Format(updateSQL, chekEmployeeid, acceptanceQty, lossQty, checkNote, containercheckinfoid));
                }
            }
            else
            {
                var insertSQL = @"insert into containerfinishedcheckinfo(containerfinishedcheckinfoid,containerid,workflowstepid,checkerid,checkqty,acceptanceqty,lossqty,createdate,checknote,isuse)
                                values('{0}','{1}','{2}','{3}','{4}','{5}','{6}',to_date('{7}','yyyy-MM-dd hh24:mi:ss'),'{8}','0');";
                var updateSQL = @"UPDATE containerfinishedcheckinfo SET checkerid='{0}',acceptanceqty='{1}',lossqty='{2}',checknote='{3}'
                            WHERE containerfinishedcheckinfoid='{4}'";
                var containerfinishedcheckinfoid = OracleHelper.GetSingle(string.Format("select containerfinishedcheckinfoid from containerfinishedcheckinfo e where e.containerid ='{0}' and workflowstepid='{1}'", containerId, workflowstepID));
                if (containerfinishedcheckinfoid == null)
                {
                    arrList.Add(string.Format(insertSQL, uuid, containerId, workflowstepID, chekEmployeeid, acceptanceQty, acceptanceQty, lossQty, createDate, checkNote));
                }
                else
                {
                    arrList.Add(string.Format(updateSQL, chekEmployeeid, acceptanceQty, lossQty, checkNote, containerfinishedcheckinfoid));
                }

            }
            #endregion
            #region "批量带子序号"
            var insert = @"INSERT INTO CHECKQTYCHANGERECORD(checkqtychangerecordid,containerid,containercheckinfoid,containerstepworkreportid,workflowstepid,qty,scrapsourcetype,changeqtytype,employeeid,createdate)
                          values(sys_guid(),'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}',to_date('{8}','yyyy-MM-dd hh24:mi:ss'))";
            var container = OracleHelper.Query(string.Format("select * from container e where e.parentcontainerid ='{0}'", containerId)).Tables[0];
            if (!string.IsNullOrWhiteSpace(lossQty))
            {
                foreach (var lossCN in lossContainerName.Split(',').Distinct())
                {
                    DataRow[] Row = container.Select("containername like '%" + lossCN + "%'");
                    if (Row != null&&Row.Length>0)
                    {
                        arrList.Add(string.Format(insert, Row[0]["containerId"], uuid, containerStepWorkReportID, workflowstepID, "-1", (finishCheck.Equals("0") ? "1" : "2"), "2", chekEmployeeid, createDate));
                    }
                }
                //存在报废，更新报工表--报废数量
                var update = @"UPDATE CONTAINERSTEPWORKREPORT CSW SET CSW.LOSSQTY=NVL(CSW.LOSSQTY,0) + {0} WHERE CSW.CONTAINERSTEPWORKREPORTID='{1}'";
                arrList.Add(string.Format(update, lossQty, containerStepWorkReportID));
                //存在报废，更新批次汇总表【总报废数：AllLossQty】
                arrList.Add(string.Format("update containercurrentinfo set alllossqty=NVL(alllossqty,0)+{0},qty={1} where containerId='{2}'", lossQty, acceptanceQty, containerId));
                arrList.Add(string.Format("update container set qty={0} where containerId='{1}'", acceptanceQty, containerId));
            }
            #endregion
            var msg = string.Empty;
            var result = OracleHelper.ExecuteSqlTran(arrList, ref msg);
            if (result)
            {
                return RespMsg("true", "检验信息接收成功");
            }
            else
            {
                return RespMsg("true", "检验信息接收失败:" + msg);
            }

        }
        /// <summary>
        /// 新QMS理化调用MES接口
        /// </summary>
        /// <param name="strXml"></param>
        /// <returns></returns>
        public string newQmsToMesAPI(string strXml, XmlNode mesDoc) 
        {
            var executeSql = string.Empty;
            var EntrustName = mesDoc.SelectSingleNode("entrustName").InnerText;//委托单号
            var selectEntrustID = OracleHelper.GetSingle(string.Format("select en.entrustmeasurementid from entrustmeasurement2 en where en.entrustname ='{0}' ", EntrustName));
            if (selectEntrustID==null) 
            {
                executeSql = string.Format(@"insert into entrustmeasurement2(entrustmeasurementid,entrustname,sendxml,createdate)values(sys_guid(),'{0}','{1}',sysdate)", EntrustName, strXml);
            } 
            else 
            {
                executeSql = string.Format(@"update entrustmeasurement2 set sendxml='{0}' where entrustmeasurementid='{1}'", strXml, selectEntrustID.ToString());
            }
            var result = OracleHelper.ExecuteSql(executeSql);
            if (result>0)
            {
                return RespMsg("true", "MES接收新QMS理化信息成功");
            }
            else
            {
                return RespMsg("true", "MES接收新QMS理化信息失败:");
            }
        }
        /// <summary>
        /// 退料退库申请检验结果接口
        /// </summary>
        /// <param name="mesDoc"></param>
        /// <returns></returns>
        public string qmsSendReturnInbound(XmlNode mesDoc) 
        {
            var arrList = new ArrayList();
            var updateSQL = @"update StockReturnApplyBill set acceptanceqty='{0}',checkstatus=1 where  mfgorderid=(SELECT mfgorderid FROM MFGORDER m WHERE mfgordername ='{1}') 
             AND productid=(SELECT p.productid FROM PRODUCT p LEFT JOIN PRODUCTBASE pb ON pb.PRODUCTBASEID=p.PRODUCTBASEID WHERE pb.PRODUCTNAME='{2}')
             AND productbatchno='{3}'";
            XmlNodeList itemNodes = mesDoc.SelectNodes("QIS_PROCESSs/QIS_PROCESS");
            foreach (XmlNode mesNode in itemNodes)
            {
                string ORDER_NO = mesNode.SelectSingleNode("ORDER_NO").InnerText;//订单号
                string PRODUCT_CODE = mesNode.SelectSingleNode("PRODUCT_CODE").InnerText;//物料号
                string PRODUCT_NAME = mesNode.SelectSingleNode("PRODUCT_NAME").InnerText;//物料名称
                string PRODUCT_BATCH = mesNode.SelectSingleNode("PRODUCT_BATCH").InnerText;//批次号
                string ACCEPTANCEQTY = mesNode.SelectSingleNode("ACCEPTANCEQTY").InnerText;//合格数
                arrList.Add(string.Format(updateSQL, ACCEPTANCEQTY, ORDER_NO, PRODUCT_CODE, PRODUCT_BATCH));
            }
            var msg = string.Empty;
            var result = OracleHelper.ExecuteSqlTran(arrList, ref msg);
            if (result)
            {
                return RespMsg("true", "退料退库申请检验结果接收成功");
            }
            else
            {
                return RespMsg("true", "退料退库申请检验结果接收失败:" + msg);
            }
        }

    }
}